import {createContext, Suspense, useEffect, useState} from 'react'
import './App.less'
import Footer from './components/TabBar/Index'
import {Outlet, useLocation} from 'react-router-dom'
// import FingerprintJS from '@fingerprintjs/fingerprintjs'
import {useRequest} from "ahooks";
// @ts-ignore
import {wechatAuthLogin,setupAgentConfig} from "./utils/wechat";
import { getVipInfo } from './api';

export interface appStoreProps {
    vip: string,
    count: number,
    isSubscribe: boolean,
}

const appStoreDefaultValue: appStoreProps = {
    vip: '0',
    count: 0,
    isSubscribe: false,
}

export const appStoreContext = createContext<appStoreProps>(appStoreDefaultValue)

function App() {
    
    // const fpPromise = FingerprintJS.load()

    // const loginHandler = async () => {
    //     let res = await fpPromise.then(fp => fp.get())
    //     return await login({
    //         isBrowser: true,
    //         visitorId: res.visitorId,
    //     });
    // }

    // const {data, error, run} = useRequest(loginHandler, {
    //     manual: true, onSuccess: (res) => {
    //         console.log(res)
    //         localStorage.setItem('token', res?.data?.token)
    //         setToken(localStorage.getItem('token') || '')
    //     }
    // })

    const [token, setToken] = useState<string>(sessionStorage.getItem('token') || '')
    useEffect(() => {
        if (!token) {
            wechatAuthLogin().then((res:any) => {
                console.log(res)
                if (res?.data?.token) {
                    sessionStorage.setItem('token', res?.data?.token)
                    sessionStorage.setItem('userInfo', JSON.stringify(res?.data?.userInfo) || '')
                    setToken(sessionStorage.getItem('token') || '')
                }
            }).catch((err:any) => {
                console.log(err)
            })
        }

        setupAgentConfig()
    }, [])

    // 监听有了token后再获取用户信息
    useEffect(() => {
        if (token) {
            getMyVipInfo()
        }
    }, [token])


    const location = useLocation()

    const { pathname } = location

    const showFooter = ['/', '/pushNote', '/vipNoteList', '/my'].includes(pathname)

    const [appState, setAppState] = useState<appStoreProps>(appStoreDefaultValue)
    
    const getMyVipInfo = async () => {
        let res = await getVipInfo()
        setAppState(res.data)
     }

    return (
        <appStoreContext.Provider value={appState}>
            <div className="App">
                {token && <Outlet />}
                {showFooter && <Footer/>}
            </div>
        </appStoreContext.Provider>
    )
}

export default App
